package com.example.chessbattleplatform.web.room_board.websocket;


import cn.hutool.json.JSONUtil;
import com.example.chessbattleplatform.Interceptor.WebSocketSetUserConfigurator;
import com.example.chessbattleplatform.Pojo.WebSocketSessionIdAndUserId;
import com.example.chessbattleplatform.utils.WebSocketSessionSendMessage;
import com.example.chessbattleplatform.web.room_board.Pojo.dto.UpdatePiecesDto;
import com.example.chessbattleplatform.web.room_board.Service.impl.RoomBoardServiceInterface;
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@ServerEndpoint(value = "/ws/gaming", configurator = WebSocketSetUserConfigurator.class)
public class ChessRoomWebSocketServer {
    // 查询数据库 查看 房间的 红方id 和 黑方id
    // 查询sessionMap 获取到对应的session
    // 在将 红方 和 黑方 分别发送给对应的sessio
    // 制作 定时 任务 检测是否双方都已经连接
    // 检测到双方都已经连接后，再发送消息给双方
    // 链接关闭时，删除对应的session

    // 存储所有的session
    public static final WebSocketSessionSendMessage webSocketSessionSendMessage = new WebSocketSessionSendMessage();
    // 导入业务层
    private static RoomBoardServiceInterface roomBoardService;

    @Autowired
    public void setRoomBoardService(RoomBoardServiceInterface roomBoardService) {
        ChessRoomWebSocketServer.roomBoardService = roomBoardService;
    }

    // 链接成功
    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {

        // 获取token 并 校验
        Long user_id = Long.valueOf((String) config.getUserProperties().get("user_Id"));

        // 存储session
        webSocketSessionSendMessage.addSessionMap(session, WebSocketSessionIdAndUserId.builder().userId(user_id).session(session).build());

        webSocketSessionSendMessage.sendSuccessMessage(roomBoardService.getRoom(user_id), session);
    }

    // 接收消息
    @OnMessage
    public void onMessage(Session session, String message) {
        System.out.println("收到消息:" + message);
        try {

            UpdatePiecesDto bean = JSONUtil.toBean(message, UpdatePiecesDto.class);
            log.info("json 转化{}", bean);

        } catch (Exception ignored) {
            String id = session.getId();
            log.info("session id{}\"不是Json\"", id);

            webSocketSessionSendMessage.sendSuccessMessage("不是Json", session);
        }

    }

    // 链接关闭
    @OnClose
    public void onClose(Session session) {


        WebSocketSessionIdAndUserId remove = webSocketSessionSendMessage.deleteSessionMap(session);

        System.out.println(session + "链接关闭,删除：" + remove);
    }


}
